package com.shunda.system.service.impl;

import com.shunda.common.core.domain.entity.SysUser;
import com.shunda.system.domain.SysUserDutyLog;
import com.shunda.system.mapper.SysUserDutyLogMapper;
import com.shunda.system.service.ISysUserDutyLogService;
import com.shunda.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: dongyq
 * @date: 2025/3/26 16:22
 * @since: 1.0.0
 * @功能描述:
 */
@Service
public class SysUserDutyLogServiceImpl implements ISysUserDutyLogService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserDutyLogMapper sysUserDutyLogMapper;

    @Override
    public void changeUserDutyLog(SysUser user) {
        SysUserDutyLog log = copyUserToLog(user);
        // 修改该用户上一状态的endTime字段
        sysUserDutyLogMapper.updateUserBeforeDutyLogEndTime(log.getUserId(), getNotStatus(log.getStatus()));
        // 新增该用户本次状态记录
        sysUserDutyLogMapper.insertUserDutyLog(log);
    }

    @Override
    public List<SysUserDutyLog> selectUserDutyLog(String deptId, String userId) {
        return sysUserDutyLogMapper.selectUserDutyLog(deptId, userId);
    }

    public SysUserDutyLog copyUserToLog(SysUser user) {
        SysUserDutyLog log = new SysUserDutyLog();
        Long deptId = user.getDeptId();
        if (deptId == null) {
            deptId = userService.selectUserById(user.getUserId()).getDeptId();
        }
        log.setDeptId(deptId);
        log.setUserId(user.getUserId());
        log.setStatus(user.getStatus());
        return log;
    }

    public String getNotStatus(String status) {
        if ("0".equals(status)) {
            return "1";
        }
        if ("1".equals(status)) {
            return "0";
        }
        return null;
    }
}
